/*public class Test {
}*/
public class Test {
    public static int knapsack(int[] weights, int[] values, int capacity) {
        int n = weights.length;
        int[][] dp = new int[n + 1][capacity + 1];

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= capacity; j++) {
                if (weights[i - 1] > j) {
                    dp[i][j] = dp[i - 1][j];
                } else {
                    dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + values[i - 1]);
                }
            }
        }

        // 回溯找出选中的物品
        boolean[] selected = new boolean[n];
        int j = capacity;
        for (int i = n; i > 0; i--) {
            if (dp[i][j] != dp[i - 1][j]) {
                selected[i - 1] = true;
                j -= weights[i - 1];
            }
        }

        System.out.print("选中的物品索引（从 0 开始）：");
        for (int i = 0; i < n; i++) {
            if (selected[i]) {
                System.out.print(i + " ");
            }
        }
        System.out.println();

        return dp[n][capacity];
    }

    public static void main(String[] args) {
        int[] weights = {2, 3, 4, 5};
        int[] values = {3, 4, 5, 6};
        int capacity = 8;
        int maxValue = knapsack(weights, values, capacity);
        System.out.println("背包能装的最大价值：" + maxValue);
    }
}
